package com.jin.spirng_boot_learn.untils;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author l04111
 * @date 2018/4/25
 * spring容器中Bean实例的获取
 */

@Component
public class BeanTool implements ApplicationContextAware {

    private ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }


    public ApplicationContext getContext() {
        return context;
    }


    /**
     * 根据类型获取Bean
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T getBean(Class<T> tClass) {
        return context.getBean(tClass);
    }

    /**
     * 根据类名获取Bean
     * @param className
     * @param <T>
     * @return
     */
    public <T> T getBean(String className) {
        return (T) context.getBean(className);
    }

    /**
     * 根据类名和类型精确地获取Bean
     * @param className
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T getBean(String className,Class<T> tClass) {
        return context.getBean(className,tClass);
    }


}
